package top.houry.netty.barrage.netty;

import cn.hutool.core.util.ObjectUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import top.houry.netty.barrage.attr.BarrageLimitAttrInfo;
import top.houry.netty.barrage.consts.BarrageChannelAttrConst;


@Slf4j
public class WebSocketNettyServerTrafficStatisticsHandler extends ChannelInboundHandlerAdapter {

    /**
     * 读取发送的消息
     *
     * @param ctx     通道上下文
     * @param barrage 信息内容
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object barrage) throws Exception {
        doTrafficStatistics(ctx);
        ctx.fireChannelRead(barrage);
    }

    private static void doTrafficStatistics(ChannelHandlerContext ctx) {
        BarrageLimitAttrInfo barrageLimitAttrInfo = ctx.channel().attr(BarrageChannelAttrConst.NETTY_CHANNEL_LIMIT_ATTR).get();
        if (ObjectUtil.isNull(barrageLimitAttrInfo)) {
            ctx.channel().attr(BarrageChannelAttrConst.NETTY_CHANNEL_LIMIT_ATTR).set(new BarrageLimitAttrInfo(100, 60 * 1000));
        } else {
            barrageLimitAttrInfo.inc();
        }
    }


}
